//
//  SignUpBrain.m
//  tradersOnMap
//
//  Created by bilmuh bilmuh on 11.03.2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SignUpBrain.h"


@implementation SignUpBrain

@synthesize email, password, password2, firstName, lastName, error;

- (void)signUp
{
	if (email == NULL) {
		UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"E-mail Error" message:@"Please fill the e-mail box." 
													delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
		[av show];
		[av release];
	}else if (![password isEqualToString:password2]) {
		UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Password Error" message:@"The passwords do not match, try again." 
													delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
		[av show];
		[av release];
	}else if (password == NULL) {
		UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Password Error" message:@"Please fill the password box." 
													delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
		[av show];
		[av release];
	}else {
		[self sendToServer];
		[userId release];
		[error release];
	}
}

-(void)sendToServer
{
	NSString *urlstr = [[NSString alloc] initWithFormat:@"http://sorubank.ege.edu.tr/~b05067683/tez/signUp.php?email=%@&password=%@&ad=%@&soyad=%@",email,password,firstName,lastName];
	NSURL *url = [[NSURL alloc] initWithString:urlstr];
	NSURLRequest *urlReq = [NSURLRequest requestWithURL:url];
	[[NSURLConnection alloc] initWithRequest:urlReq delegate:self];
	userId = [[NSString alloc] init];
	error = [[NSString alloc] init];
	
	//receiving data and parsing
	NSData *data = [NSData dataWithContentsOfURL:url];
	NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
	[parser setDelegate:self];
	[parser parse];
	[parser release];
}

- (void)parser:(NSXMLParser *)parser 
didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qualifiedName
	attributes:(NSDictionary *)attributeDict
{
	textInProgress = [[NSMutableString alloc] init];
}

- (void)parser:(NSXMLParser *)parser
 didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
{
	if ([elementName isEqual:@"id"]) {
		NSUserDefaults *defaults = [[NSUserDefaults alloc] init];
		[defaults setInteger:[textInProgress integerValue] forKey:@"userID"];
		[defaults release];
	}else if ([elementName isEqual:@"error"]) {
		error = textInProgress;
	}
}

- (void)parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string
{
    [textInProgress appendString:string];
}

@end
